package client;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import utilities.ANSI;

/**
 * The Class ClientListener.
 * 
 * @author Nils Berlijn
 * @author Henderikus Harms
 * @version 1.0
 * @since June 1, 2014
 */
public class ClientListener implements Runnable
{
	/** The client listener socket. */
	private ServerSocket clientListenerSocket;
	
	/** The client queue. */
	private ClientQueue<Runnable> clientQueue;		
	
	/** The listen. */
	private boolean listen;
	
	/** The client connection. */
	private Socket clientConnection;

	/**
	 * Instantiates a new client listener.
	 *
	 * @param port the port
	 * @param clientQueue the client queue
	 */
	public ClientListener(int port, ClientQueue<Runnable> clientQueue)
	{
		try 
		{
			this.clientListenerSocket = new ServerSocket(port);
			
			System.out.println(ANSI.GREEN + "Client Listener is successfully launched." + ANSI.NORMAL);
			
			this.clientQueue = clientQueue;
			this.listen = true;				
			
			System.out.println(ANSI.YELLOW + "Client Listener is waiting for incoming connections...\n" + ANSI.NORMAL);
		} 
		catch(IOException e) 
		{
			this.listen = false;
						
			System.out.println(ANSI.RED + "Client Listener is not successfully launched!\n" + ANSI.NORMAL);
		}
	}

	/* (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run()
	{	
		while(listen == true)
		{		
			try 
			{
				clientConnection = clientListenerSocket.accept();
				
				System.out.println(ANSI.BLUE + "Client Listener: " + ANSI.GREEN + "\"" + clientConnection.getInetAddress() + "\" has established a new connection" + ANSI.NORMAL);

				try 
				{
					clientQueue.add(new ClientWorker(clientConnection));
					
					System.out.println(ANSI.BLUE + "Client Listener: " + ANSI.YELLOW + "\"" + clientConnection.getInetAddress() + "\" has been added to the queue" + ANSI.NORMAL);	
				} 
				catch(InterruptedException e) 
				{
					System.out.println(ANSI.BLUE + "Client Listener: " + ANSI.RED + "\"" + clientConnection.getInetAddress() + "\" has not been added to the queue" + ANSI.NORMAL);	
				}
			} 
			catch(IOException e) 
			{
				System.out.println(ANSI.RED + "Client Listener: " + ANSI.RED + "Someone has failed by trying too establishing a new connection" + ANSI.NORMAL);
			}			
		}
	}
}